<template>
  <div>
    <el-tabs type="border-card" class="informationLabel">
      <el-tab-pane label="标签生成">
        <el-row :gutter="20">
          <el-col :span="11">
            <avue-form ref="form" v-model="form" :option="option" @submit="handleGenerateBarcode"></avue-form>
          </el-col>
          <el-col :span="12">
            <div class="sequenceInfo">
              <table border="1">
                <tr>
                  <th colspan="4">序列号规则</th>
                </tr>
                <tr>
                  <th>规则名称</th>
                  <th>
                    <el-tooltip class="item" effect="dark" placement="top-start">
                      <i class="el-icon-info" style="color: #606266"></i>
                      <div slot="content">
                        [P]：前缀字符,[YY]：两位年份, [YYYY]：四位年份, [M]：月,<br />[W]：周, [D]：日, [S]：流水号, [N]：自定义字符。<br />[B]：后缀字符 <br />如：[YY][M][S][B]
                        <br />若无流水号则没有[S],例如：[YY][M][B]
                      </div>
                      <!-- <el-button style="padding: 0; font-size: 18px" type="info" icon="el-icon-info" circle></el-button> -->
                    </el-tooltip>
                    序列号规则
                    <el-button
                      v-if="
                        sequenceRuleInfo.sequenceNoFormat &&
                        (sequenceRuleInfo.sequenceNoFormat.indexOf('[YYYY]') > -1 ||
                          sequenceRuleInfo.sequenceNoFormat.indexOf('[YY]') > -1 ||
                          sequenceRuleInfo.sequenceNoFormat.indexOf('[M]') > -1 ||
                          sequenceRuleInfo.sequenceNoFormat.indexOf('[W]') > -1 ||
                          sequenceRuleInfo.sequenceNoFormat.indexOf('[D]') > -1)
                      "
                      style="padding: 5px"
                      type="primary"
                      icon="el-icon-edit"
                      circle
                      @click="openTimeConfigModel"
                    ></el-button>
                  </th>
                  <th>序列号规则位数</th>
                  <th>当前流水号</th>
                </tr>
                <tr style="height: 40px">
                  <td>{{ sequenceRuleInfo.name }}</td>
                  <td>
                    <div>{{ sequenceRuleInfo.sequenceNoFormat }}</div>
                    <div>{{ sequenceRuleInfo.sequenceNoFormatZh }}</div>
                  </td>
                  <td>
                    <div>{{ sequenceRuleInfo.snLength }}</div>
                  </td>
                  <td>{{ sequenceRuleInfo.sequenceNo }}</td>
                </tr>
              </table>
              <el-row>
                <el-col :span="15">
                  <div class="custom-title"><i class="el-icon-vertical-bar mr10"></i>包装配置</div>
                  <div class="number-desc">
                    <span class="valid-code">*</span>包装层级1(小包)：1个小包，装
                    <el-input-number controls-position="right" v-model="pageInfo.packQuantitySpecFirst"></el-input-number>
                    (单位)物料
                  </div>
                  <div class="number-desc">
                    <span class="valid-code">*</span>包装层级2(大包)：1个大包，装
                    <el-input-number v-model="pageInfo.subPackQuantitySecond" controls-position="right" :min="1"></el-input-number>
                    个小包
                  </div>
                </el-col>
                <el-col :span="15" class="btn-group">
                  <el-button type="primary" size="small" @click="handleCreatLabel">生成条码 </el-button>
                  <el-button type="primary" size="small" @click="handleViewDetail" v-prevent-re-click :disabled="!isHaveData"> 条码详情 </el-button>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
    <el-tabs type="border-card" class="informationLabel" style="margin-top: 12px">
      <el-tab-pane label="标签打印">
        <el-row :gutter="20">
          <el-col :span="10">
            <div class="custom-title"><i class="el-icon-vertical-bar mr10"></i>打印配置</div>
            <barcode-printer-template ref="printInfo" templateType="MATERIAL" @getPrintInfo="getPrintInfo"></barcode-printer-template>
          </el-col>
          <el-col :span="10">
            <div class="custom-title"><i class="el-icon-vertical-bar mr10"></i>打印操作</div>
            <el-col :span="10">
              <div>
                大包数量:
                {{ pageInfo.packGenerationDetailQtySecond && pageInfo.packGenerationDetailQtySecond.packQuantity }}
              </div>
              <el-col :span="10">
                <div>整箱:{{ pageInfo.packGenerationDetailQtySecond && pageInfo.packGenerationDetailQtySecond.fullPackQuantity }}</div>
                <div>
                  已打印:<span class="color-green">{{ pageInfo.packGenerationDetailQtySecond && pageInfo.packGenerationDetailQtySecond.printedPackQuantity }}</span>
                </div>
              </el-col>
              <el-col :span="10">
                <div>尾箱:{{ pageInfo.packGenerationDetailQtySecond && pageInfo.packGenerationDetailQtySecond.tailPackQuantity }}</div>
                <div>
                  未打印:<span class="valid-code">{{ pageInfo.packGenerationDetailQtySecond && pageInfo.packGenerationDetailQtySecond.notPrintPackQuantity }}</span>
                </div>
              </el-col>
            </el-col>
            <el-col :span="10">
              <div>小包数量:{{ pageInfo.packGenerationDetailQtyFirst && pageInfo.packGenerationDetailQtyFirst.packQuantity }}</div>
              <el-col :span="10">
                <div>整箱:{{ pageInfo.packGenerationDetailQtyFirst && pageInfo.packGenerationDetailQtyFirst.fullPackQuantity }}</div>
                <div>
                  已打印: <span class="color-green">{{ pageInfo.packGenerationDetailQtyFirst && pageInfo.packGenerationDetailQtyFirst.printedPackQuantity }}</span>
                </div>
              </el-col>
              <el-col :span="10">
                <div>尾箱:{{ pageInfo.packGenerationDetailQtyFirst && pageInfo.packGenerationDetailQtyFirst.tailPackQuantity }}</div>
                <div>
                  未打印:<span class="valid-code">{{ pageInfo.packGenerationDetailQtyFirst && pageInfo.packGenerationDetailQtyFirst.notPrintPackQuantity }}</span>
                </div>
              </el-col>
            </el-col>
            <el-col :span="15" class="btn-group">
              <el-button type="primary" size="small" @click="handlePrintBigPack" v-prevent-re-click :disabled="isDisabledBigPrintBtn || !isHaveData">打印大包标签 </el-button>
              <el-button type="primary" size="small" @click="handlePrintSmallPack" v-prevent-re-click :disabled="isDisabledSmallPrintBtn || !isHaveData">
                打印小包标签
              </el-button>
            </el-col>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
    <recive-dialog ref="reciveDialog" :option="tableOption" @getSelectedRows="getSelectedRows"></recive-dialog>
    <el-dialog append-to-body title="序列号规则时间修改" :visible.sync="timeConfigModel" width="30%">
      <avue-form ref="timeConfigForm" v-model="timeConfig" :option="timeConfigOption"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="onSaveTimeConfig"><i class="el-icon-circle-plus-outline"></i><span>保 存</span></el-button>
        <el-button size="small" @click="timeConfigModel = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <!--其他信息弹窗-->
    <el-dialog append-to-body title="其他信息" :visible.sync="otherInfoDialog" width="30%">
      <div class="form-contant" v-if="fieldList.length">
        <avue-form ref="otherInfo" v-model="otherInfo" :option="otherInfoOption" @submit="otherInfoSubmit"></avue-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="saveOtherInfo"><i class="el-icon-circle-plus-outline"></i><span>保 存</span></el-button>
        <el-button size="small" @click="otherInfoDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>

    <el-dialog append-to-body title="重打" v-if="printInfoModel" :visible.sync="printInfoModel" width="35%">
      <div style="display: flex; justify-content: center; margin-bottom: 10px">
        <span style="color: red">注：仅需修改流水号即可，重打的起始流水号和结束流水号需在原流水号范围内</span>
      </div>
      <avue-form ref="printForm" v-model="repeatPrintInfo" :option="printInfoOption"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="printSubmit"><i class="el-icon-printer"></i><span>重打</span></el-button>
        <el-button size="small" @click="printInfoModel = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>

    <!-- 生成条码     -->
    <el-dialog append-to-body :title="dialogTitle" :visible.sync="barcodeDialog" width="50%">
      <div class="sail-header-dialog-content">
        <avue-crud
          ref="bigCrud"
          :option="bigPackOption"
          :data="bigPackData"
          :table-loading="bigLoading"
          :page.sync="bigPage"
          @selection-change="selectionChange"
          @size-change="sizeChange"
          @current-change="currentChange"
        >
          <template slot="menuLeft">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-delete"
              plain
              v-if="dialogTitle === '条码详情'"
              @click="handleMultiBigPackReprint"
              :disabled="!selectionList.length"
              >重 打
            </el-button>
          </template>
          <template slot-scope="{ row }" slot="menu">
            <el-button type="text" size="small" @click="handleViewSmallPack(row)">小包详情</el-button>
            <el-button type="text" size="small" v-if="dialogTitle === '条码详情'" @click="handleReprint(row)" :disabled="row.status === 1">重打 </el-button>
          </template>
        </avue-crud>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="barcodeDialog = false" v-if="dialogTitle !== '条码详情'">取消生成</el-button>
        <el-button size="small" @click="handleConfirm" v-if="dialogTitle !== '条码详情'">确认生成</el-button>
      </span>
    </el-dialog>

    <el-dialog append-to-body title="小包详情" :visible.sync="smallDialog" width="50%">
      <div class="sail-header-dialog-content">
        <avue-crud
          ref="smallCrud"
          :option="smallPackOption"
          :data="smallPackData"
          :table-loading="smallLoading"
          :page.sync="smallPage"
          @selection-change="detailSelectionChange"
          @size-change="detailSizeChange"
          @current-change="detailCurrentChange"
        >
          <template slot="menuLeft">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-delete"
              plain
              v-if="dialogTitle === '条码详情'"
              @click="handleMultiSmallPackReprint"
              :disabled="!selectionList.length"
              >重 打
            </el-button>
          </template>
          <template slot-scope="{ row }" slot="menu">
            <el-button type="text" size="small" v-if="dialogTitle === '条码详情'" :disabled="row.status === 1" @click="handleReprint(row)">重打 </el-button>
          </template>
        </avue-crud>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getBigPackOption, getOption, getSmallPackOption } from '@/views/product/refactor/barcodeGeneration.js';
import barcodePrinterTemplate from '@/views/product/components/barcode-printer-template.vue';
import { getYearWeek } from '@/util/helpers';
import reciveDialog from '@/views/product/components/reciveDialog.vue';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { getSeqNoRules } from '@/util/global';
import {
  generationInOutSourceList,
  getInOutSourceList,
  inOutPrint,
  inOutReprint,
  inOutSourceList,
  previewGenerationInOutSourceList
} from '@/api/warehouse/warehouse-label-create-print';
import { packPrint } from '@/api/admin/barcode-record';

export default {
  name: 'inOutGeneration',
  components: { CommonModalTemplate, reciveDialog, barcodePrinterTemplate },
  data() {
    return {
      form: {},
      isHaveData: false,
      fieldList: [],
      otherInfoDialog: false,
      barcodeDialog: false,
      smallDialog: false,
      smallDisable: false,
      bigDisable: false,
      selectionList: [],
      detailSelection: [],
      otherInfo: {},
      pageInfo: {},
      printInfo: {},
      configValue: 'false', //参数管理的逻辑 先留着以防变卦
      option: getOption(this),
      smallPackOption: getSmallPackOption(this),
      bigPackOption: getBigPackOption(this),
      bigPackData: [],
      bigLoading: false,
      smallLoading: false,
      smallPackData: [],
      repeatPrintInfo: {},
      sequenceRuleInfo: {},
      dialogTitle: '生成条码',
      tableOption: {},
      timer: new Date().getTime(),
      otherInfoOption: {
        submitBtn: false,
        emptyBtn: false,
        column: []
      },
      timeConfigModel: false, //序列号规则时间修改模态框是否显示
      timeConfig: {}, //序列号规则时间配置
      timeConfigOption: {
        //序列号规则时间修改内容配置
        labelWidth: 150,
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '年代码',
            prop: 'year',
            type: 'year',
            format: 'yyyy',
            valueFormat: 'yyyy',
            span: 20,
            display: false
          },
          {
            label: '月代码',
            prop: 'month',
            type: 'month',
            format: 'MM',
            valueFormat: 'MM',
            span: 20,
            display: false
          },
          {
            label: '周代码',
            prop: 'week',
            span: 20,
            display: false
          },
          {
            label: '日代码',
            prop: 'day',
            type: 'date',
            format: 'dd',
            valueFormat: 'dd',
            span: 20,
            display: false,
            change(val) {
              console.log(val, Date.parse(val), Object.prototype.toString.call(Date.parse(val)));
            }
          }
        ]
      },
      bigPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      smallPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      parentId: '',
      printInfoModel: false,
      printInfoOption: {
        labelWidth: 150,
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '标签模版',
            prop: 'labelTemplateName',
            span: 20,
            type: 'search',
            placeholder: '请选择 标签模板',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择标签模板',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openLabelTemplateModal();
            }
          },
          {
            label: '打印机',
            prop: 'equipmentName',
            span: 20,
            type: 'search',
            placeholder: '请选择 打印机',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择打印机',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openPrintersModal();
            }
          }
        ]
      }
    };
  },
  computed: {
    isDisabledBigPrintBtn() {
      const printedPackQuantity = this.pageInfo.packGenerationDetailQtySecond && this.pageInfo.packGenerationDetailQtySecond.notPrintPackQuantity;
      return printedPackQuantity === 0 || this.bigDisable;
    },
    isDisabledSmallPrintBtn() {
      const printedPackQuantity = this.pageInfo.packGenerationDetailQtyFirst && this.pageInfo.packGenerationDetailQtyFirst.notPrintPackQuantity;
      return printedPackQuantity === 0 || this.smallDisable;
    }
  },
  methods: {
    /**
     * 序列号规则时间修改
     */
    openTimeConfigModel() {
      this.timeConfigModel = true;
      this.timeConfig.year = this.timeConfig.year ? this.timeConfig.year : this.$moment().format('YYYY');
      this.timeConfig.month = this.timeConfig.month ? this.timeConfig.month : this.$moment().format('MM');
      this.timeConfig.week = this.timeConfig.week ? this.timeConfig.week : getYearWeek();
      this.timeConfig.day = this.timeConfig.day ? this.timeConfig.day : this.$moment().format('DD');
      this.$nextTick(() => {
        let column = this.$refs.timeConfigForm.option.column;
        if (
          (this.sequenceRuleInfo.sequenceNoFormat && this.sequenceRuleInfo.sequenceNoFormat.indexOf('[YYYY]') > -1) ||
          this.sequenceRuleInfo.sequenceNoFormat.indexOf('[YY]') > -1
        ) {
          let year = this.findObject(column, 'year');
          year.display = true;
        }
        if (this.sequenceRuleInfo.sequenceNoFormat && this.sequenceRuleInfo.sequenceNoFormat.indexOf('[M]') > -1) {
          let month = this.findObject(column, 'month');
          month.display = true;
        }
        if (this.sequenceRuleInfo.sequenceNoFormat && this.sequenceRuleInfo.sequenceNoFormat.indexOf('[W]') > -1) {
          let week = this.findObject(column, 'week');
          week.display = true;
        }
        if (this.sequenceRuleInfo.sequenceNoFormat && this.sequenceRuleInfo.sequenceNoFormat.indexOf('[D]') > -1) {
          let day = this.findObject(column, 'day');
          day.display = true;
        }
      });
    },
    async getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'otherReceiveMoal':
          try {
            this.$refs.otherInfo && this.$refs.otherInfo.resetFields();
            //动代码的时候注意 configValue  === 'true' 是核达 rowData is Array  else 是产品通用 rowData is Object
            if (this.configValue === 'true') {
              let flag = this._some(rowData, (item) => {
                return item.labelGenerationStatus == 1;
              });
              if (flag) {
                this.$message.warning('已完成代表在(原材料包装条码打印)中不可打印，需在(原材料包装条码增补)页面打印');
                return;
              }
              if (rowData.length === 0) {
                this.$refs.reciveDialog.hideModal();
                return;
              }
              const isCanCheck = this.arePropertiesEqual(rowData, 'vendorCode', 'partNo', 'inspectionLotNo');
              if (!isCanCheck) {
                this.$message.warning('选中的收料记录中有不属于同一个供应商同一个物料同一个检验批次的，请重新选择！');
              } else {
                const info = rowData[0];
                const sheetNoList = [];
                rowData.forEach((item) => {
                  if (item.sheetNo) {
                    sheetNoList.push(item.sheetNo);
                  }
                });
                this.form.receiveRecord = sheetNoList.join(',') || '其他收料';
                this.partId = this._get(info, 'partMasterId', '');
                this.form.receivingId = rowData.map((item) => item.id).join(',');
                this.form.partId = this._get(info, 'partMasterId', '');
                this.form.partNo = this._get(info, 'partNo', '');
                this.form.partName = this._get(info, 'partName', '');
                this.form.partModel = this._get(info, 'partModel', '');
                this.form.sequenceDefinitionId = this._get(info, 'packingSeqDefinitionId', '');
                this.form.sequenceName = this._get(info, 'packSeqDefinitionName', '');
                let receiveQuantity = 0;
                let quantityPrinted = 0;
                rowData.forEach((item) => {
                  let value = Number(item.receiveQuantity);
                  receiveQuantity += value;
                  let quantityPrintedValue = Number(item.quantityPrinted);
                  quantityPrinted += quantityPrintedValue;
                });
                this.form.receiveQuantity = receiveQuantity;
                // minPackingQuantity 优先 receivingOption.mpq
                this.form.vendorDate = this._get(info, 'vendorDate', '');
                this.form.vendorLotNo = this._get(info, 'vendorLotNo', '');
                this.form.vendorCode = this._get(info, 'vendorCode', '');
                this.form.vendorName = this._get(info, 'vendorName', '');
                this.form.uom = this._get(info, 'uom', '');
                //this._get(info, 'quantityPrinted', '');
                this.form.quantityPrinted = quantityPrinted;
                this.form.remark = '';
                this.form.inspectionLotNo = this._get(info, 'inspectionLotNo', '');
                this.form.partLotNo = this._get(info, 'dateCode', '');
                this.form.materialBrand = this._get(info, 'materialBrand', '');

                const labelTemplateId = this._get(info, 'labelTemplateId', '');
                const labelTemplateName = this._get(info, 'labelTemplateName', '');
                this.$refs.printInfo.setPrintLabel(labelTemplateId, labelTemplateName);
                this.printInfo.labelTemplateId = labelTemplateId;
                this.printInfo.dataId = this._get(info, 'dataId', '');
                if (this.printInfo.dataId) {
                  this.getDetail(this.printInfo.dataId);
                }
                this.$refs.reciveDialog.hideModal();
                if (Number(this.form.actuallyReceive)) {
                  this.form.generationQuantity = Number(this.form.actuallyReceive) - (Number(this.form.quantityPrinted) || 0);
                }
                if (!info.labelTemplateId || !info.packingSeqDefinitionId) {
                  await this.setDefaultInfo(info.partNo);
                }
                if (this.form.sequenceDefinitionId) {
                  this.getSequencedefinitionDetail(this.form.sequenceDefinitionId);
                }
                this.getInoutById(this.form.receivingId);
              }
            } else {
              if (Object.keys(rowData).length === 0) {
                return;
              }
              if (rowData.labelGenerationStatus === 1) {
                this.$message.warning('已完成代表在(原材料包装条码打印)中不可打印，需在(原材料包装条码增补)页面打印');
                return;
              }
              this.form.receiveRecord = rowData.sheetNo || '其他收料';
              this.partId = this._get(rowData, 'partMasterId', '');
              this.form.receivingId = this._get(rowData, 'id', '');
              this.form.partId = this._get(rowData, 'partMasterId', '');
              this.form.partNo = this._get(rowData, 'partNo', '');
              this.form.partName = this._get(rowData, 'partName', '');
              this.form.partModel = this._get(rowData, 'partModel', '');
              this.form.sequenceDefinitionId = this._get(rowData, 'packingSeqDefinitionId', '');
              this.form.sequenceName = this._get(rowData, 'packSeqDefinitionName', '');
              this.form.receiveQuantity = rowData.receiveQuantity;
              this.form.uom = this._get(rowData, 'uom', '');
              // minPackingQuantity 优先 receivingOption.mpq
              this.form.vendorDate = this._get(rowData, 'vendorDate', '');
              this.form.vendorLotNo = this._get(rowData, 'vendorLotNo', '');
              this.form.vendorCode = this._get(rowData, 'vendorCode', '');
              this.form.vendorName = this._get(rowData, 'vendorName', '');
              this.form.quantityPrinted = this._get(rowData, 'quantityPrinted', '');
              this.form.remark = '';
              this.form.inspectionLotNo = this._get(rowData, 'inspectionLotNo', '');
              this.form.partLotNo = this._get(rowData, 'dateCode', '');
              this.form.materialBrand = this._get(rowData, 'materialBrand', '');

              const labelTemplateId = this._get(rowData, 'labelTemplateId', '');
              const labelTemplateName = this._get(rowData, 'labelTemplateName', '');
              this.$refs.printInfo.setPrintLabel(labelTemplateId, labelTemplateName);
              this.printInfo.labelTemplateId = labelTemplateId;
              this.printInfo.dataId = this._get(rowData, 'dataId', '');
              if (this.printInfo.dataId) {
                this.getDetail(this.printInfo.dataId);
              }

              if (Number(this.form.receiveQuantity)) {
                this.form.generationQuantity = Number(this.form.receiveQuantity) - (Number(this.form.quantityPrinted) || 0);
              }
              // if (!rowData.labelTemplateId || !rowData.packingSeqDefinitionId) {
              //   await this.setDefaultInfo(rowData.partNo);
              // }
              if (this.form.sequenceDefinitionId) {
                this.getSequencedefinitionDetail(this.form.sequenceDefinitionId);
              }

              this.getInoutById(this.form.receivingId);
            }
          } catch (e) {
            console.warn(e);
          }

          break;
        case 'serialnoModal':
          this.form.sequenceName = this._get(rowData, 'name', '');
          this.form.sequenceDefinitionId = this._get(rowData, 'id', '');
          this.sequenceRuleInfo.id = this._get(rowData, 'id', '');
          this.sequenceRuleInfo.name = this._get(rowData, 'name', '');
          this.sequenceRuleInfo.sequenceNo = this._get(rowData, 'sequenceNo', '');
          this.sequenceRuleInfo.sequenceNoFormat = this._get(rowData, 'sequenceNoFormat', '');
          this.sequenceRuleInfo.sequenceNoFormatZh = this._get(rowData, 'sequenceNoFormatZh', '');
          this.sequenceRuleInfo.seqNoFormatDemo = this._get(rowData, 'seqNoFormatDemo', '');
          this.sequenceRuleInfo.containsSequenceNo = this._get(rowData, 'containsSequenceNo', true);
          this.sequenceRuleInfo.charactersCount = this._get(rowData, 'charactersCount', 0);
          this.seqNoConvert();
          break;
        case 'printersModal':
          this.repeatPrintInfo.equipmentId = this._get(rowData, 'id', '');
          this.repeatPrintInfo.equipmentName = this._get(rowData, 'name', '');
          break;
        case 'labelTemplateModal':
          this.repeatPrintInfo.labelTemplateId = this._get(rowData, 'id', '');
          this.repeatPrintInfo.labelTemplateName = this._get(rowData, 'name', '');
          break;
        default:
          break;
      }
    },
    newKey() {
      this.timer = new Date().getTime();
    },
    onSaveTimeConfig() {
      //验证是否传递序列号规则中年份日期
      if (
        (this.sequenceRuleInfo.sequenceNoFormat && this.sequenceRuleInfo.sequenceNoFormat.indexOf('[YYYY]') > -1) ||
        this.sequenceRuleInfo.sequenceNoFormat.indexOf('[YY]') > -1
      ) {
        if (!this.timeConfig.year) {
          this.$message({
            type: 'error',
            message: '请选择序列号规则中的年份！'
          });
          return;
        }
      }
      if (this.sequenceRuleInfo.sequenceNoFormat && this.sequenceRuleInfo.sequenceNoFormat.indexOf('[M]') > -1) {
        if (!this.timeConfig.month) {
          this.$message({
            type: 'error',
            message: '请选择序列号规则中的月份！'
          });
          return;
        }
      }
      if (this.sequenceRuleInfo.sequenceNoFormat && this.sequenceRuleInfo.sequenceNoFormat.indexOf('[W]') > -1) {
        if (!this.timeConfig.week) {
          this.$message({
            type: 'error',
            message: '请输入序列号规则中的周数！'
          });
          return;
        }
      }
      if (this.sequenceRuleInfo.sequenceNoFormat && this.sequenceRuleInfo.sequenceNoFormat.indexOf('[D]') > -1) {
        if (!this.timeConfig.day) {
          this.$message({
            type: 'error',
            message: '请选择序列号规则中的日期！'
          });
          return;
        }
      }
      this.timeConfigModel = false;
    },
    async otherInfoSubmit(row, done) {
      try {
        // 去除row中包含 $的key
        const otherInfo = this.filterChart(row);
        await this.handlePrintSequence(otherInfo);
        this.otherInfoDialog = false;
      } catch (e) {
        console.log(e);
      } finally {
      }
      done();
    },
    saveOtherInfo() {
      this.$refs.otherInfo.submit();
    },
    openCommonModal(type) {
      // sheetNoModal / otherReceiveMoal
      this.modalName = type;

      this.$refs.reciveDialog.showModal();
      let url;
      if (type === 'otherReceiveMoal') {
        url = `/api/mes-warehouse/receiving/page`;
      }
      this.tableOption = {
        modalTitle: `请选择收料记录（双击进行选择）`,
        url,
        isPage: true,
        rowSelectionType: this.configValue === 'true' ? '' : 'single',
        openSubmitCheck: this.configValue === 'true',
        searchLabelWidth: 120,
        searchSpan: 8,
        height: 280,
        columnBtn: true,
        refreshBtn: true,
        columnDefs: [
          {
            label: '单据号',
            prop: 'sheetNo',
            search: true
          },
          {
            label: '供应商编码',
            prop: 'vendorCode',
            search: true
          },
          {
            label: '供应商名称',
            prop: 'vendorName',
            search: true
          },
          {
            label: '物料编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '物料名称',
            prop: 'partName',
            search: true
          },
          {
            label: '物料规格',
            prop: 'partModel'
          },
          {
            label: '收料数量',
            prop: 'receiveQuantity'
          },
          // {
          //   label: '实收数量',
          //   prop: 'actuallyReceive'
          // },
          // {
          //   label: '已生成数量',
          //   prop: 'quantityPrinted'
          // },
          /* {
                label: '标签生成状态',
                prop: 'labelGenerationStatus',
                type: 'select',
                dicData: [
                  {
                    label: '已完成',
                    value: 1
                  },
                  {
                    label: '未完成',
                    value: 0
                  }
                ],
                search: true
              },*/
          {
            label: '单位',
            prop: 'uom'
          },

          {
            label: '生产日期',
            prop: 'vendorDate'
          },
          {
            label: 'D/C',
            prop: 'dateCode'
          },
          {
            label: '品牌',
            prop: 'productBrand'
          },
          {
            label: '供应商批次',
            prop: 'vendorLotNo'
          },
          {
            label: '收料人',
            prop: 'receivingByName'
          },
          {
            label: '收料时间',
            prop: 'createTime',
            search: true,
            hide: true,
            searchSpan: 12,
            type: 'date',
            searchType: 'datetimerange',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
          },
          {
            label: '收料时间',
            prop: 'receiveTime'
          },
          {
            label: '送检单号',
            prop: 'examineNo'
          }
        ]
      };
    },
    /**
     * 打开序列号规则选择模态框
     */
    openSerialnoCommonModal() {
      this.modalName = 'serialnoModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择序列号规则（双击进行选择）',
        url: '/api/mes-admin/sequencedefinition/page?type=material&subTypeStr=RAW_MATERIAL_PACKAGING,ACCESSORIES',
        isPage: true,
        rowSelectionType: 'single',
        // searchMenuPosition: 'left',
        searchMenuSpan: 24,
        columnDefs: [
          {
            label: '大类',
            prop: 'type',
            type: 'select',
            dicData: [{ label: '物料', value: 'MATERIAL' }]
          },
          {
            label: '小类',
            prop: 'subType',
            searchSpan: 8,
            dicData: [
              { label: '原材料包装', value: 'RAW_MATERIAL_PACKAGING' },
              { label: '辅料', value: 'ACCESSORIES' }
            ],
            type: 'select',
            search: true
          },
          {
            label: '序列号规则名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '序列号规则编码',
            prop: 'code',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '起始流水号',
            prop: 'startSequenceNo'
          },
          {
            label: '结束流水号',
            prop: 'endSequenceNo'
          },
          {
            label: '序列号规则',
            prop: 'sequenceNoFormat'
          }
        ]
      };
    },

    /**
     * 获取打印机
     */
    openPrintersModal() {
      this.modalName = 'printersModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择打印机（双击进行选择）',
        url: '/api/mes-product/ems-equipment/page?type=PRINTER',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '打印机编码',
            prop: 'code',
            search: true,
            searchLabelWidth: 110
          },
          {
            label: '打印机名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 110
          }
        ]
      };
    },
    /**
     * 打开标签模板模态框
     */
    openLabelTemplateModal() {
      this.modalName = 'labelTemplateModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择标签模版（双击进行选择）',
        url: '/api/mes-admin/labeltemplate/page?status=1&type=MATERIAL&subTypeStr=RAW_MATERIAL_PACKAGING,ACCESSORIES',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '大类',
            prop: 'type',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=dalei',
            cascader: ['subType'],
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            // change: ({ column, value }) => {
            //   this.getSubTypeData(value);
            // },
            search: true
          },
          {
            label: '小类',
            prop: 'subType',
            // dicUrl: '/api/blade-system/dict/dictionary?code={{key}}',
            // props: {
            //   label: 'dictValue',
            //   value: 'dictKey'
            // },
            formatter: (row) => {
              const subTypeMap = {
                WORKORDER: '工单',
                FLOW_CARD: '流程卡',
                WAREHOUSE: '仓库',
                WORKSTATION: '产线（工位）',
                STORAGE_AREA: '存储区域',
                EQUIPEMENT: '设备及其属性',
                TOOL: '工装/夹具',
                VEHICLE: '载具',
                INSPECTION_RESULTS: '检验结果',
                FAULT_PHENOMENON: '故障现象/故障类别',
                RAW_MATERIAL_PACKAGING: '原材料包装',
                WORK_IN_PROGRESS: '在制品',
                FINISHED_PRODUCT_PACKAGING: '成品包装',
                ACCESSORIES: '辅料',
                PALLET: '栈板',
                SCM_DO: 'SCM送货单'
              };
              return subTypeMap[row.subType] || '';
            },
            fromslot: true,
            type: 'select',
            search: true
          },
          {
            label: '模板名称',
            prop: 'name',
            search: true
          },
          {
            label: '模版代码',
            prop: 'code',
            search: true
          },
          {
            label: '版本名称',
            prop: 'version'
          },
          {
            label: '缩略图',
            prop: 'thumbnailUrl'
          },
          {
            label: '标签地址',
            prop: 'fileUrl'
          },
          {
            label: '打印列数',
            prop: 'columnCount'
          },
          {
            label: '打印份数',
            prop: 'copies'
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      };
    },
    /*
     * 序列号规则转换中文
     * @param sequenceNoValue 序列号规则
     * @param sequenceNo 序列号规则起始流水号
     */
    seqNoConvert() {
      let seqNoRules = [];
      this._forEach(getSeqNoRules(), (item) => {
        seqNoRules = [...seqNoRules, ...item.value];
      });
      let splitList = this.sequenceRuleInfo.sequenceNoFormat.split('');
      //在[前加空格  ]后加空格
      splitList = splitList.map((item) => {
        if (item === '[') {
          return ' [';
        } else if (item === ']') {
          return '] ';
        } else {
          return item;
        }
      });
      splitList = splitList.join('');
      //按空格拆分字符串
      splitList = splitList.split(' ');
      //匹配中文
      let splitArr = this._map(splitList, (item) => {
        this._forEach(seqNoRules, (ele) => {
          if (item === ele.key) {
            item = ele.value;
          }
        });
        return item;
      });
      //去除空格
      splitArr = splitArr.filter(function (s) {
        return s && s.trim();
      });
      //转换后给序列号规则赋值
      this.sequenceRuleInfo.sequenceNoFormatZh = splitArr.join('+');
    },
    getInoutById(id) {
      let params = {
        receivingId: id
      };
      getInOutSourceList(params).then(
        (res) => {
          if (res.data.data) {
            this.pageInfo = res.data.data || {};
            this.isHaveData = Object.keys(this.pageInfo).length > 0;
          } else {
            this.pageInfo = {};
            this.isHaveData = false;
          }
        },
        (error) => {
          console.warn(error);
        }
      );
    },
    /**
     * 获取打印机和打印模版信息
     */
    getPrintInfo(printInfo) {
      if (printInfo.printersId) {
        this.printInfo.printersId = printInfo.printersId;
      }
      if (printInfo.labelTemplateId) {
        this.printInfo.labelTemplateId = printInfo.labelTemplateId;
        const dataId = printInfo.dataId;
        if (dataId) {
          this.getDetail(printInfo.dataId);
        } else {
          this.fieldList = [];
        }
      }
    },
    handleGenerateBarcode() {},
    async handleCreatLabel() {
      if (!this.form.partNo) {
        this.$message({
          type: 'warning',
          message: '请选择收料记录!'
        });
        return;
      }
      if (!this.form.sequenceName) {
        this.$message({
          type: 'warning',
          message: '请选择序列号规则!'
        });
        return;
      }

      if (!this.form.vendorDate) {
        this.$message({
          type: 'warning',
          message: '请选择生产日期!'
        });
        return;
      }
      if (!this.form.generationQuantity) {
        this.$message({
          type: 'warning',
          message: '请输入本次生成数量!'
        });
        return;
      }
      if (!this.pageInfo.packQuantitySpecFirst) {
        this.$message({
          type: 'warning',
          message: '请输入1个小包包含的物料数量！'
        });
        return;
      }
      const packQuantitySpecFirst = this.pageInfo.packQuantitySpecFirst;
      if (!Number.isInteger(packQuantitySpecFirst) || packQuantitySpecFirst <= 0) {
        this.$message({
          type: 'warning',
          message: '1个小包包含的物料数量需为正整数！'
        });
        return;
      }
      if (!this.pageInfo.subPackQuantitySecond) {
        this.$message({
          type: 'warning',
          message: '请输入1个大包包含的小包数量！'
        });
        return;
      }
      const subPackQuantitySecond = this.pageInfo.subPackQuantitySecond;
      if (!Number.isInteger(subPackQuantitySecond) || subPackQuantitySecond <= 0) {
        this.$message({
          type: 'warning',
          message: '1个大包包含的小包数量需为正整数！'
        });
        return;
      }
      this.dialogTitle = '生成条码';
      this.smallPage.total = 0;
      this.bigPage.total = 0;
      this.setBigColumn();
      this.setSmallColumn();
      const params = this.getParams();
      const res = await previewGenerationInOutSourceList(params);
      this.bigPackData = (res.data.data || []).map((item) => {
        return {
          ...item,
          child: item.children,
          children: []
        };
      });
      this.barcodeDialog = true;
    },
    getParams() {
      const params = {
        receivingId: this.form.receivingId, //   收料记录id
        sequenceDefinitionId: this.form.sequenceDefinitionId, //   序列号规则配置ID
        subPackQuantitySecond: this.pageInfo.subPackQuantitySecond, //   2级包可包的1级包数量
        packQuantitySpecFirst: this.pageInfo.packQuantitySpecFirst, //   1级包规（物料数量）
        generateQuantity: this.form.generationQuantity, //   本次生成数量
        vendorLotNo: this.form.vendorLotNo, //   供应商批次
        //  inspectionLotNo: this.form.inspectionLotNo, //   检验批次
        dateCode: this.form.dateCode, //   D/C
        brand: this.form.brand, //   品牌
        vendorDate: this.form.vendorDate, //   生产日期
        remark: this.form.remark //   备注
      };
      return params;
    },
    async handleConfirm() {
      try {
        const params = this.getParams();
        const res = await generationInOutSourceList(params);
        this.$message.success('生成成功');
        this.getInoutById(this.form.receivingId);
        this.barcodeDialog = false;
      } catch (e) {
        console.log(e);
      }
    },
    handleViewSmallPack(row) {
      this.smallDialog = true;
      if (this.dialogTitle === '生成条码') {
        this.smallPackData = row.child;
      } else {
        this.parentId = row.id;
        this.getSmallDetail();
      }
    },
    printSubmit() {
      this.$refs.printForm.validate(async (valid, done) => {
        if (valid) {
          try {
            const params = {
              equipmentId: this.repeatPrintInfo.equipmentId, //   打印机id
              labelMaterialIdSet: [this.repeatPrintInfo.id],
              labelTemplateId: this.repeatPrintInfo.labelTemplateId //   标签模板id
            };
            const res = await inOutReprint(params);
            this.$message.success('重打成功');
            this.printInfoModel = false;
          } catch (e) {
            console.warn(e);
          }
        }
      });
    },
    handleReprint(row) {
      this.repeatPrintInfo.id = row.id;
      this.printInfoModel = true;
    },
    async handleViewDetail() {
      if (!this.form.receivingId) {
        this.$message({
          type: 'warning',
          message: '请选择收料记录!'
        });
        return;
      }
      this.dialogTitle = '条码详情';
      await this.getBigDetail();
      this.setBigColumn();
      this.setSmallColumn();
      this.barcodeDialog = true;
    },
    async getBigDetail() {
      try {
        const params = {
          receivingId: this.form.receivingId,
          parentId: -1
        };
        const res = await inOutSourceList(params);
        const data = res.data.data;
        this.bigPage.total = data.total;
        this.bigPackData = data.records;
      } catch (e) {
        console.log(e);
      }
    },
    async getSmallDetail() {
      try {
        const params = {
          receivingId: this.form.receivingId,
          parentId: this.parentId
        };
        const res = await inOutSourceList(params);
        const data = res.data.data;
        this.smallPage.total = data.total;
        this.smallPackData = data.records;
      } catch (e) {
        console.log(e);
      }
    },
    handleMultiBigPackReprint() {
      if (this.selectionList.some((item) => item.status !== 2)) {
        this.$message.warning('请选择状态为已打印的条码进行重打');
        return;
      }
      this.repeatPrintInfo.id = this.selectionList.map((item) => item.id);
      this.printInfoModel = true;
    },
    handleMultiSmallPackReprint() {
      if (this.detailSelection.some((item) => item.status !== 2)) {
        this.$message.warning('请选择状态为已打印的条码进行重打');
        return;
      }
      this.repeatPrintInfo.id = this.detailSelection.map((item) => item.id);
      this.printInfoModel = true;
    },
    async handlePrintBigPack() {
      if (!this.checkoutPrintInfo()) {
        return;
      }
      const params = this.getPrintParams(2);
      try {
        const res = await inOutPrint(params);
        this.$message.success('打印成功');
        this.getInoutById(this.form.receivingId);
        this.bigDisable = true;
        this.smallDisable = false;
      } catch (e) {}
    },
    checkoutPrintInfo() {
      if (!this.printInfo.printersId) {
        this.$message.warning('‘请选择打印机’');
        return false;
      }
      if (!this.printInfo.labelTemplateId) {
        this.$message.warning('请选择标签模板');
        return false;
      }
      return true;
    },
    async handlePrintSmallPack() {
      if (!this.checkoutPrintInfo()) {
        return;
      }
      const params = this.getPrintParams(1);
      try {
        const res = await inOutPrint(params);
        this.$message.success('打印成功');
        this.getInoutById(this.form.receivingId);
        this.bigDisable = false;
        this.smallDisable = true;
      } catch (e) {}
    },
    sizeChange(pageSize) {
      this.bigPage.pageSize = pageSize;
      this.getBigDetail();
    },
    currentChange(currentPage) {
      this.bigPage.currentPage = currentPage;
      this.getBigDetail();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    detailSizeChange(pageSize) {
      this.smallPage.pageSize = pageSize;
      this.getBigDetail();
    },
    detailCurrentChange(currentPage) {
      this.smallPage.currentPage = currentPage;
      this.getBigDetail();
    },
    detailSelectionChange(list) {
      this.detailSelection = list;
    },
    getPrintParams(level) {
      const params = {
        receivingId: this.form.receivingId, // 收料记录id
        equipmentId: this.printInfo.printersId, // 打印机id
        labelTemplateId: this.printInfo.labelTemplateId, // 标签模板id
        level // 标签层级
      };
      return params;
    },
    setBigColumn() {
      let column = this.bigPackOption.column;
      if (this.dialogTitle !== '生成条码') {
        column = [
          {
            label: '包装条码',
            prop: 'sequenceNumber'
          },
          {
            label: '包装层级',
            prop: 'level',
            formatter: (val) => {
              return '大包';
            }
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            dicData: [
              {
                label: '未打印',
                value: 1
              },
              {
                label: '已打印',
                value: 2
              },
              {
                label: '已报废',
                value: 3
              },
              {
                label: '已使用',
                value: 4
              }
            ]
          },
          {
            label: '小包数量',
            prop: 'subPackQuantity'
          }
        ];
      } else {
        column = [
          {
            label: '包装条码',
            prop: 'sequenceNumber'
          },
          {
            label: '小包数量',
            prop: 'subPackQuantity'
          }
        ];
      }
      this.$set(this.bigPackOption, 'column', column);
      // this.$refs.bigCrud.refreshTable();
    },
    setSmallColumn() {
      let column = this.smallPackOption.column;
      if (this.dialogTitle === '生成条码') {
        column = [
          {
            label: '包装条码',
            prop: 'sequenceNumber'
          },
          {
            label: '包装数量',
            prop: 'quantity'
          }
        ];
      } else {
        column = [
          {
            label: '包装条码',
            prop: 'sequenceNumber'
          },
          {
            label: '包装层级',
            prop: 'level',
            formatter: (val) => {
              return '小包';
            }
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            dicData: [
              {
                label: '未打印',
                value: 1
              },
              {
                label: '已打印',
                value: 2
              },
              {
                label: '已报废',
                value: 3
              },
              {
                label: '已使用',
                value: 4
              }
            ]
          },
          {
            label: '包装数量',
            prop: 'quantity'
          }
        ];
      }
      this.$set(this.smallPackOption, 'column', column);
    }
  }
};
</script>

<style scoped lang="scss">
.sequenceInfo {
  table {
    width: 100%;
    height: auto;
    margin-bottom: 10px;
    font-size: 14px;

    th {
      border: 1px solid #ebeef5;
      background: #fafafa;
      height: 30px;
    }

    tr {
      border: 1px solid #ebeef5;
    }

    td {
      border: 1px solid #ebeef5;
      height: auto;
      text-align: center;
    }

    p {
      margin-left: 30px;
    }
  }
}

.custom-title {
  font-size: 16px;
  font-weight: bold;
  margin: 10px 0;

  i {
    margin-right: 10px;
  }
}

.color-green {
  color: green;
}

.valid-code {
  color: red;
}

.number-desc {
  font-size: 14px;
}

.btn-group {
  display: flex;
  justify-content: center;
}
</style>
